import io
import PIL.Image as Image
import torchvision.transforms.functional as F
import requests
import numpy
import torch


def get_points(host, filename, version=1.0):
    f = open(filename, 'rb')
    b = f.read()
    f.close()
    res0 = requests.post(f'http://{host}/predictions/detect/{version}', data={'data': b})
    box = torch.tensor(res0.json()['box']).int()
    stream = io.BytesIO(b)
    arr = numpy.asarray(Image.open(stream))

    cropped_arr = arr[box[1]:box[3], box[0]:box[2], :]
    image = Image.fromarray(cropped_arr)
    output_stream = io.BytesIO()
    image.save(output_stream, 'jpeg')
    res1 = requests.post(f'http://{host}/predictions/pose/{version}', data={'data': output_stream.getvalue()})
    points = torch.tensor(res1.json())
    points = torch.round(points + box[0:2]).int()
    return res0.status_code == 200 and res1.status_code == 200


def test_serve_batch():
    code = get_points("10.11.153.13:60080", "./resources/images/0.jpg", version=1.0)
    return code


import threading


class PressureTestThread(threading.Thread):
    def __init__(self):
        super().__init__()

    def run(self):
        code = test_serve_batch()
        print(f"{self.name}, status_code:{'ok' if code else 'error'}")


if __name__ == '__main__':
    for i in range(100):
        PressureTestThread().start()
